package com.iflyun.rabbitmq.controller;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;

import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.iflyun.rabbitmq.model.WeChatLog;
import com.iflyun.rabbitmq.model.WebLog;





public class UserLogs {
	

	
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

	/**
	 * 微信日志对象
	 * @param request
	 * @param response
	 * @param list
	 * @param userid
	 * @param openid
	 * @param title
	 * @param operationType
	 * @param GPS_x
	 * @param GPS_y
	 * @param mobilePhoneBrand
	 * @param operatingSystem
	 * @param productVersion
	 * @param productCode
	 */
	public void WeChatLogSave(HttpServletRequest request,
			HttpServletResponse response, List<String> list, String userid,
			String openid, String title, String operationType, float GPS_x,
			float GPS_y, String mobilePhoneBrand, String operatingSystem,
			String productVersion, String productCode) {
		
		final HttpServletRequest req=request;
		final HttpServletResponse res=response;
		final List<String> l=list;
		final String uid=userid;
		final String oid=openid;
		final String t=title;
		final String oType=operationType;
		final float gps_x=GPS_x;
		final float gps_y=GPS_y;
		final String mBrand=mobilePhoneBrand;
		final String oSystem=operatingSystem;
		final String pVersion=productVersion;
		final String pCode=productCode;
		
		final ExecutorService exec = Executors.newFixedThreadPool(1);
		
		Callable<String> call = new Callable<String>() {
			public String call() throws Exception {
				// 开始执行耗时操作
				ServletContext sc = req.getSession().getServletContext();
				ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(sc);
				AmqpTemplate   rabbitMQMessage = (AmqpTemplate)ac2.getBean("amqpTemplate");

				String requestUrl = req.getRequestURI().replace(
						req.getContextPath(), "");

				WeChatLog weChatLog = new WeChatLog();
				if (l != null) {
					for (int i = 0; i < l.size(); i++) {
						if (requestUrl.contains(l.get(i))) {
							return "";
						}
					}
				}
				
				weChatLog.setId(UUID.randomUUID().toString());
				weChatLog.setUserId(StringUtils.isBlank(uid) ? "" : uid);
				weChatLog.setIp(getIpAddr(req));
				weChatLog.setProxyIp(req.getRemoteAddr());
				weChatLog.setOpenId(StringUtils.isBlank(oid) ? "" : oid);
				weChatLog.setUrlAbsoluteUri(req.getRequestURL().toString());
				weChatLog.setJumpUrl("");
				weChatLog.setTitle(StringUtils.isBlank(t) ? "" : t);
				weChatLog.setPhysicalPath(requestUrl);
				weChatLog.setRequestMode(req.getMethod());
				weChatLog.setRequestParameter(StringUtils.isBlank(req.getQueryString()) ? "" : URLDecoder.decode(
						req.getQueryString(), "UTF-8"));
				weChatLog.setOperationType(StringUtils.isBlank(oType) ? "": oType);
				weChatLog.setUrlHost(req.getRemoteHost());
				weChatLog.setUrlPort(String.valueOf(req.getRemotePort()));
				weChatLog.setBrowseTime("");
				weChatLog.setGPS_X(gps_x);
				weChatLog.setGPS_Y(gps_y);
				weChatLog.setMobilePhoneBrand(StringUtils.isBlank(mBrand) ? "": mBrand);
				weChatLog.setOperationSystem(StringUtils.isBlank(oSystem) ? "": oSystem);
				weChatLog.setAccessTime(df.format(new Date()));
				weChatLog.setProductVersion(StringUtils.isBlank(pVersion) ? "": pVersion);
				weChatLog.setProductCode(StringUtils.isBlank(pCode) ? "": pCode);
				

				rabbitMQMessage.convertAndSend("wechat_key", weChatLog);

				return "";
				

			}

			
		};
		try {
			Future<String> future = exec.submit(call);
			// 任务处理超时时间设为0.5秒
			future.get(500, TimeUnit.MILLISECONDS); 
			}
		catch (TimeoutException ex) {  
            System.out.println("发送超时啦(0.5秒)....");  
            ex.printStackTrace(); 
        }catch (Exception e) {
			System.out.println("发送失败.");
			e.printStackTrace();
		}
		// 关闭线程池
		exec.shutdown();
		
		/*ServletContext sc = request.getSession().getServletContext();
		ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(sc);
		AmqpTemplate   rabbitMQMessage = (AmqpTemplate)ac2.getBean("amqpTemplate");

		String requestUrl = request.getRequestURI().replace(
				request.getContextPath(), "");

		WeChatLog weChatLog = new WeChatLog();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				if (requestUrl.contains(list.get(i))) {
					return;
				}
			}
		}

		try {
			weChatLog.setId(UUID.randomUUID().toString());
			weChatLog.setUserId(StringUtils.isBlank(userid) ? "" : userid);
			weChatLog.setIp(this.getIpAddr(request));
			weChatLog.setProxyIp(request.getRemoteAddr());
			weChatLog.setOpenId(StringUtils.isBlank(openid) ? "" : openid);
			weChatLog.setUrlAbsoluteUri(request.getRequestURL().toString());
			weChatLog.setJumpUrl("");
			weChatLog.setTitle(StringUtils.isBlank(title) ? "" : title);
			weChatLog.setPhysicalPath(requestUrl);
			weChatLog.setRequestMode(request.getMethod());
			weChatLog.setRequestParameter(StringUtils.isBlank(request
					.getQueryString()) ? "" : URLDecoder.decode(
					request.getQueryString(), "UTF-8"));
			weChatLog.setOperationType(StringUtils.isBlank(operationType) ? ""
					: operationType);
			weChatLog.setUrlHost(request.getRemoteHost());
			weChatLog.setUrlPort(String.valueOf(request.getRemotePort()));
			weChatLog.setBrowseTime("");
			weChatLog.setGPS_X(GPS_x);
			weChatLog.setGPS_Y(GPS_y);
			weChatLog
					.setMobilePhoneBrand(StringUtils.isBlank(mobilePhoneBrand) ? ""
							: mobilePhoneBrand);
			weChatLog
					.setOperationSystem(StringUtils.isBlank(operatingSystem) ? ""
							: operatingSystem);
			weChatLog.setAccessTime(df.format(new Date()));
			weChatLog
					.setProductVersion(StringUtils.isBlank(productVersion) ? ""
							: productVersion);
			weChatLog.setProductCode(StringUtils.isBlank(productCode) ? ""
					: productCode);
			

			rabbitMQMessage.convertAndSend("wechat_key", weChatLog);

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
*/
	}

	/**
	 * 网站日志对象
	 * @param request
	 * @param response
	 * @param list
	 * @param userid
	 * @param title
	 * @param operationType
	 * @param productVersion
	 * @param productCode
	 */
	public void WebLogSave(HttpServletRequest request,
			HttpServletResponse response, List<String> list, String userid,
			String title, String operationType, String productVersion,
			String productCode) {
		
		final HttpServletRequest req=request;
		//final HttpServletResponse res=response;
		final List<String> l=list;
		final String uid=userid;
		final String t=title;
		final String oType=operationType;
		final String pVersion=productVersion;
		final String pCode=productCode;
		final ExecutorService exec = Executors.newFixedThreadPool(1);
		
		Callable<String> call = new Callable<String>() {
			public String call() throws Exception {
				// 开始执行耗时操作
				ServletContext sc = req.getSession().getServletContext();
				ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(sc);

				AmqpTemplate   rabbitMQMessage = (AmqpTemplate)ac2.getBean("amqpTemplate");

				String requestUrl = req.getRequestURI().replace(req.getContextPath(), "");

				WebLog webLog = new WebLog();
				if (l != null) {
					for (int i = 0; i < l.size(); i++) {
						if (requestUrl.contains(l.get(i))) {
							return "";
						}
					}
				}
				
				UserAgent userAgent = UserAgent.parseUserAgentString(req.getHeader("User-Agent"));
				// 客户端信息
				Browser browser = userAgent.getBrowser();
				OperatingSystem operatingSystem = userAgent.getOperatingSystem();

				webLog.setId(UUID.randomUUID().toString());
				webLog.setUserId(StringUtils.isBlank(uid) ? "" : uid);
				webLog.setIp(getIpAddr(req));
				webLog.setProxyIp(req.getRemoteAddr());
				//webLog.setCookieId("B2949150715B403E1B3B4EC62EB64F5E");
				webLog.setCookieId(getCookie(req));
				webLog.setUrlAbsoluteUri(req.getRequestURL()==null?"":req.getRequestURL().toString());
				//webLog.setUrlAbsoluteUri("http://172.16.7.38:8080/demo/home");
				webLog.setJumpUrl("");
				webLog.setTitle(StringUtils.isBlank(t) ? "" : t);
				webLog.setPhysicalPath(requestUrl);
				webLog.setRequestMode(req.getMethod());
				webLog.setRequestParameter(StringUtils.isBlank(req.getQueryString()) ? "" : URLDecoder.decode(
						req.getQueryString(), "UTF-8"));
				webLog.setOperationType(StringUtils.isBlank(oType) ? ""
						: oType);
				webLog.setUrlHost(req.getRemoteHost());
				webLog.setUrlPort(String.valueOf(req.getRemotePort()));
				webLog.setBrowseTime("");
				webLog.setIsMobileDevice(operatingSystem.getDeviceType().toString()
						.contains("MOBILE") ? "Y" : "N");
				webLog.setBrowser(browser.toString());
				webLog.setBrowserVersion(userAgent.getBrowserVersion() == null ? ""
						: userAgent.getBrowserVersion().toString());
				webLog.setAccessTime(df.format(new Date()));
				webLog.setProductVersion(StringUtils.isBlank(pVersion) ? ""
						: pVersion);
				webLog.setProductCode(StringUtils.isBlank(pCode) ? "": pCode);

				//发送消息
				rabbitMQMessage.convertAndSend("weblog_key", webLog);

				return "";
				

			}

			
		};

		try {
			Future<String> future = exec.submit(call);
			// 任务处理超时时间设为0.5秒
			future.get(500, TimeUnit.MILLISECONDS); 
			}
		catch (TimeoutException ex) {  
            System.out.println("发送超时啦(0.5秒)....");  
            ex.printStackTrace(); 
        }catch (Exception e) {
			System.out.println("发送失败.");
			e.printStackTrace();
		}
		// 关闭线程池
		exec.shutdown();
			

	}

	/**
	 * 获取Ip地址
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.indexOf(",") != -1) {
			ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		}
		return ip;
	}

	/**
	 * 获取cookie
	 */
	public String getCookie(HttpServletRequest request) {
		String cookie = "";
		Cookie[] cookies = request.getCookies();
		if(cookies==null)
		{
			return "test";
		}
		for (int i = 0; i < cookies.length; i++) {
			if ("JSESSIONID".equals(cookies[i].getName())) {
				cookie = cookies[i].getValue();
				break;
			}
		}
		return cookie;
	}

}
